<?php
header('Content-Type: application/json');
error_reporting(E_ALL);
ini_set('display_errors', 1);

try {
    if (!isset($_GET['id'])) {
        throw new Exception('缺少ID参数');
    }

    $id = $_GET['id'];
    
    // 读取 books.json
    $booksFile = __DIR__ . '/../../data/books.json';
    if (!file_exists($booksFile)) {
        throw new Exception('书籍数据文件不存在');
    }

    $books = json_decode(file_get_contents($booksFile), true);
    if (!isset($books['books'])) {
        throw new Exception('数据格式错误');
    }

    // 查找指定 ID 的书籍
    $book = null;
    foreach ($books['books'] as $item) {
        if ($item['id'] == $id) {
            $book = $item;
            break;
        }
    }

    if (!$book) {
        throw new Exception('未找到指定的书籍');
    }

    error_log("Loading book {$id}, content length: " . strlen($book['content']));

    echo json_encode([
        'success' => true,
        'data' => [
            'id' => $book['id'],
            'title' => $book['title'],
            'content' => $book['content'],
            'contentImages' => $book['contentImages'],
            'cover' => $book['cover'] ? "/admin/uploads/books/covers/{$book['cover']}" : null
        ]
    ]);

} catch (Exception $e) {
    error_log('Get Error: ' . $e->getMessage());
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
?> 